<template>
  <div class="mt-16 mb-8">
    <a-space>
      <a-input :style="{width:'320px'}" placeholder="请输入规则组名" allow-clear v-model="chartName"/>
      <a-input :style="{width:'320px'}" placeholder="请输入规则组唯一编号" allow-clear v-model="chartCode"/>
      <a-button type="primary" @click="initData">搜索</a-button>
    </a-space>
  </div>
  <div class="w-full text-right mb-3">
    <a-button type="primary" status="success" @click="addModalVisible=true"
              :disabled="projectCode === undefined || projectCode == null || projectCode === ''">新增
    </a-button>
  </div>
  <a-table :columns="columns"
           :data="tableData"
           :pagination="page">
    <template #isActive="{ record }">
      <a-switch v-model="record.isActive"
                :checked-value="1"
                :unchecked-value="0"
                @change="active(record)"
      >
        <template #checked>
          激活中
        </template>
        <template #unchecked>
          未激活
        </template>
      </a-switch>
    </template>
    <template #activeInfo="{ record }">
      <!--      {{record}}-->
      <a-tag @click="$modal.info({ title:'版本信息', content:record?.activeVersionInfo?.introduce })"
             class="cursor-pointer"
             :color="record?.activeVersionInfo?.code===record?.versionList[record.versionList.length-1]?.code?'purple':'orange'"
      >{{ record?.activeVersionInfo?.name }}
      </a-tag>
      <a-tooltip content="当前激活版本不是最新版本" position="right">
        <icon-info-circle-fill
            v-if="record?.activeVersionInfo?.code!==record?.versionList[record.versionList.length-1]?.code"/>
      </a-tooltip>
    </template>
    <template #versionList="{ record }">
      <a-space>
        <a-select :default-value="record.activeVersionInfo.name"
                  v-model="record.waitActiveVersionCode"
                  :style="{width:'120px'}"
                  placeholder="Select"
                  :trigger-props="{ autoFitPopupMinWidth: true }">
          <a-option v-for="item of record.versionList"
                    :value="item.code"
                    :label="item.name"/>
        </a-select>
        <icon-plus-circle size="20" class="cursor-pointer" @click="openAddVersionModal(record)"/>
        <a-button @click="changeVersion(record)" status="success"
                  :disabled="record.activeVersionInfo.code === record.waitActiveVersionCode">切换
        </a-button>
        <a-button @click="goToVersionEdit(record)" status="warning">
          版本编辑
        </a-button>
      </a-space>
    </template>
    <template #optional="{ record }">
      <a-space>
        <a-button status="success" @click="openEditModal(record)">编辑</a-button>
        <a-popconfirm content="删除后无法恢复，您确定要删除吗?" @ok="deleteChartGroup(record)">
          <a-button status="danger">删除</a-button>
        </a-popconfirm>
      </a-space>
    </template>
    <template #chartName="{ record }">
      <span class="cursor-pointer"
            @click="$modal.info({ title:'规则组简介', content:record?.describe===''?'暂无简介':record?.describe })">
        {{ record.chartName }}
      </span>
    </template>
  </a-table>

  <a-modal v-model:visible="addModalVisible" title="新增规则组" :on-before-ok="addChart" @close="clearForm">
    <a-form :model="form">
      <a-form-item field="name" label="规则组名称" required>
        <a-input v-model="form.name"/>
      </a-form-item>
      <a-form-item field="describe" label="规则组描述">
        <a-textarea placeholder="请输入规则组描述" allow-clear v-model="form.describe"/>
      </a-form-item>
      <a-form-item field="isActive" label="是否激活" required>
        <a-radio-group v-model="form.isActive">
          <a-switch v-model="form.isActive" :checked-value="1" :unchecked-value="0">
            <template #checked>
              激活中
            </template>
            <template #unchecked>
              未激活
            </template>
          </a-switch>
        </a-radio-group>
      </a-form-item>
    </a-form>
  </a-modal>
  <a-modal v-model:visible="addVersionModalVisible" title="版本迭代"
           :onBeforeOk="addNewVersion"
           @close="clearVersionForm">
    <a-form :model="versionForm">
      <a-form-item field="chartCode" label="规则组编号" required>
        <a-input v-model="versionForm.chartCode" disabled/>
      </a-form-item>
      <a-form-item field="versionName" label="版本名称" required>
        <a-input v-model="versionForm.versionName"/>
      </a-form-item>
      <a-form-item field="introduce" label="版本描述">
        <a-textarea placeholder="请输入版本描述" allow-clear v-model="versionForm.introduce"/>
      </a-form-item>
    </a-form>
  </a-modal>
  <a-modal v-model:visible="editModalVisible" title="更新规则组" :on-before-ok="editChart" @close="clearForm">
    <a-form :model="form">
      <a-form-item field="name" label="规则组名称" required>
        <a-input v-model="form.name"/>
      </a-form-item>
      <a-form-item field="describe" label="规则组描述">
        <a-textarea placeholder="请输入规则组描述" allow-clear v-model="form.describe"/>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import {ref} from 'vue';
import {useRoute} from "vue-router";
import {_} from "@/http/index.js";
import {Message} from "@arco-design/web-vue";
import router from "@/router/index.js";

export default {
  setup() {
    const columns = [
      {
        title: '规则组编号',
        dataIndex: 'chartCode',
      },
      {
        title: '规则组名称',
        slotName: 'chartName',
      },
      {
        title: '是否激活',
        slotName: 'isActive',
      },
      {
        title: '激活版本信息',
        slotName: 'activeInfo',
      },
      {
        title: '版本列表',
        slotName: 'versionList',
      },
      {
        title: '最后更新时间',
        dataIndex: 'updateTime',
      },
      {
        title: '操作',
        slotName: 'optional'
      }
    ];
    const tableData = ref([]);
    let chartName = ref('');
    let chartCode = ref('');
    let projectCode = ref('');
    let addModalVisible = ref(false);
    let addVersionModalVisible = ref(false);
    let editModalVisible = ref(false);
    let form = ref({
      code: '',
      name: '',
      describe: '',
      isActive: 0,
      projectCode: ''
    });
    // 版本迭代表单
    let versionForm = ref({
      versionName: '',
      introduce: '',
      chartCode: '',
    })
    const route = useRoute();
    projectCode.value = route.query.projectCode
    let page = ref({
      current: 1,
      pageSize: 10,
      total: 0,
      showTotal: true
    })

    /**
     * 初始化数据
     */
    function initData() {
      _.chart.join(`/${projectCode.value}`).get(
          {
            query: {
              chartName: chartName.value,
              chartCode: chartCode.value,
              current: page.value.current,
              size: page.value.pageSize
            }
          }
      ).then(({data}) => {
        const records = data.data
        page.value.total = data.total
        tableData.value = []
        records.forEach((item, index) => {
          tableData.value.push({
            key: index,
            chartCode: item.code,
            chartName: item.name,
            isActive: item.isActive,
            activeVersionInfo: item.activeVersionInfo,
            versionList: item.versionList,
            waitActiveVersionCode: item?.activeVersionInfo?.code,
            describe: item.describe,
            updateTime: item.updateTime
          })
        })
      })
    }

    /**
     * 添加规则组
     */
    async function addChart(done) {
      await _.chart.post({
        body: {
          name: form.value.name,
          describe: form.value.describe,
          isActive: form.value.isActive,
          projectCode: projectCode.value
        }
      }).then(({data}) => {
        console.log(data)
        initData()
        done(true)
      }).catch((err) => {
        console.log(err)
        Message.error(err.response.data.message)
        done(false)
      })
    }

    /**
     * 清空表单
     */
    function clearForm() {
      form.value = {
        name: '',
        describe: '',
        isActive: 0,
        projectCode: ''
      }
    }

    /**
     * 切换版本信息
     * @param record 规则组信息
     */
    function changeVersion(record) {
      _.chart.join(`/${record.chartCode}/version?versionCode=${record.waitActiveVersionCode}`).patch().then(({data}) => {
        console.log(data)
        initData()
        Message.success('版本切换成功')
      }).catch((err) => {
        console.log(err)
        Message.error(err.response.data.message)
      })
    }

    /**
     * 版本迭代
     */
    async function addNewVersion(done) {
      await _.version.post({
        body: {
          versionName: versionForm.value.versionName,
          introduce: versionForm.value.introduce,
          chartCode: versionForm.value.chartCode
        }
      }).then(({data}) => {
        console.log(data)
        Message.success('版本新增成功')
        initData()
        done(true)
      }).catch((err) => {
        console.log(err)
        Message.error(err.response.data.message)
        done(false)
      })
    }

    /**
     * 清空版本迭代表单
     */
    function clearVersionForm() {
      versionForm.value = {
        versionName: '',
        introduce: '',
        chartCode: '',
      }
    }

    /**
     * 打开规则组版本迭代弹窗
     * @param record
     */
    function openAddVersionModal(record) {
      addVersionModalVisible.value = true
      versionForm.value.chartCode = record.chartCode
      versionForm.value.versionName = record.versionList[record.versionList.length - 1].name
      versionForm.value.introduce = record.versionList[record.versionList.length - 1].introduce
    }

    /**
     * 修改激活状态
     * @param record 规则组信息
     */
    function active(record) {
      _.chart.join(`/${record.chartCode}/active?activeStatus=${record.isActive}`).patch().then(({data}) => {
        console.log(data)
        initData()
      })
    }

    /**
     * 编辑规则组
     * @param done 回调函数
     */
    function editChart(done) {
      _.chart.join(`/${form.value.code}`).patch({
        body: {
          name: form.value.name,
          describe: form.value.describe,
          projectCode: projectCode.value
        }
      }).then(({data}) => {
        console.log(data)
        initData()
        Message.success('规则组信息更新成功')
        done(true)
      }).catch((err) => {
        console.log(err)
        Message.error(err.response.data.message)
        done(false)
      })
    }

    /**
     * 打开编辑规则组弹窗
     * @param record 规则组信息
     */
    function openEditModal(record) {
      form.value.code = record.chartCode
      form.value.name = record.chartName
      form.value.describe = record.describe
      editModalVisible.value = true
    }

    /**
     * 删除规则组
     * @param record 规则组信息
     */
    function deleteChartGroup(record) {
      _.chart.join(`/${record.chartCode}`).delete().then(({data}) => {
        console.log(data)
        initData()
        Message.success('规则组删除成功')
      }).catch((err) => {
        console.log(err)
        Message.error(err.response.data.message)
      })
    }

    /**
     * 跳转到编排编辑页面
     * @param record
     */
    function goToVersionEdit(record) {
      router.push({
        path: '/home',
        query: {
          chartCode: record.chartCode,
          projectCode: projectCode.value,
          versionCode: record.waitActiveVersionCode
        }
      })
    }

    initData()
    return {
      columns,
      tableData,
      initData,
      chartName,
      chartCode,
      page,
      addModalVisible,
      addVersionModalVisible,
      editModalVisible,
      addChart,
      clearForm,
      form,
      projectCode,
      changeVersion,
      addNewVersion,
      clearVersionForm,
      versionForm,
      openAddVersionModal,
      active,
      editChart,
      openEditModal,
      deleteChartGroup,
      goToVersionEdit
    }
  },
}
</script>
